// utils/screenshot.js
export function captureUni(selector:string, options = {}) {
  return new Promise((resolve, reject) => {
    // #ifndef H5
    // 获取当前页面实例（Vue3方式）
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const context = currentPage.$vm
    
    const query = uni.createSelectorQuery().in(context)
    query.select(selector).boundingClientRect()
    query.exec((res) => {
      const rect = res[0]
      if (!rect) {
        reject(new Error('未找到目标元素'))
        return
      }

      const systemInfo = uni.getSystemInfoSync()
      const pixelRatio = systemInfo.pixelRatio || 1

      const canvasWidth = rect.width * pixelRatio
      const canvasHeight = rect.height * pixelRatio

      const canvas = uni.createCanvasContext('captureCanvas', context)
      
      // 设置canvas尺寸
      uni.canvasToTempFilePath(
        {
          x: rect.left,
          y: rect.top,
          width: rect.width,
          height: rect.height,
          destWidth: canvasWidth,
          destHeight: canvasHeight,
          canvasId: 'captureCanvas',
          fileType: 'png',
          quality: 1,
          success: (res) => {
            resolve(res.tempFilePath)
          },
          fail: reject,
        },
        context
      )
    })
    // #endif
  })
}